package com.study_security.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.study_security.dto.ProjectAiDTO;
import com.study_security.service.WenxinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.study_security.mapper.ProjectAiMapper;
import java.util.*;

@Service
public class WenxinServiceImpl implements WenxinService {

    @Autowired
    private ProjectAiMapper projectAiMapper;

    @Value("${wenxin.api.key}")
    private String apiKey;

    @Value("${wenxin.secret.key}")
    private String secretKey;

    @Override
    public String getResponse(String userInput) {
        System.out.println(userInput);
        System.out.println("哈啊哈哈哈哈9999999999999999");
        String accessToken = getAccessToken();
        if (accessToken == null) {
            return "Failed to retrieve access token.";
        }

        String apiUrl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat";

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("User-Agent", "Mozilla/5.0 (compatible; WenxinJavaClient/1.0)");

        // 构建消息历史
        Map<String, Object> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", userInput);

        // 如果需要，可以添加助手的默认回复
        // Map<String, Object> assistantMessage = new HashMap<>();
        // assistantMessage.put("role", "assistant");
        // assistantMessage.put("content", "Hello! How can I assist you today?");
        // List<Map<String, Object>> messages = Arrays.asList(userMessage, assistantMessage);

        List<Map<String, Object>> messages = Collections.singletonList(userMessage);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("messages", messages);

        // 构建URL并添加access_token参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                .queryParam("access_token", accessToken);

        HttpEntity<String> request = new HttpEntity<>(JSON.toJSONString(requestBody), headers);

        try {
            System.out.println("Calling Wenxin API with URL: " + builder.toUriString());
            System.out.println("Request Body: " + JSON.toJSONString(requestBody));

            ResponseEntity<String> response = restTemplate.postForEntity(builder.toUriString(), request, String.class);
            System.out.println("Response: " + response.getBody()); // 日志

            if (response.getStatusCode().is2xxSuccessful()) {
                JSONObject jsonResponse = JSON.parseObject(response.getBody());
                // 根据实际API返回结构调整
                return jsonResponse.getString("result");
            } else {
                System.err.println("Failed API call. Status: " + response.getStatusCode());
                System.err.println("Response: " + response.getBody());
                return "Error: " + response.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred while calling the Wenxin API.";
        }
    }

    @Override
    public List<ProjectAiDTO> getProjectByProjectName(String projectName) {
        return projectAiMapper.getProjectsByProjectName(projectName);
    }


    private String getAccessToken() {
        System.out.println("哈啊哈哈哈哈66666666666666666");
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("User-Agent", "Mozilla/5.0 (compatible; WenxinJavaClient/1.0)");

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "client_credentials");
        params.add("client_id", apiKey);
        params.add("client_secret", secretKey);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

        try {
            System.out.println("Requesting access token with API Key: " + apiKey);
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                JSONObject jsonResponse = JSON.parseObject(response.getBody());
                String token = jsonResponse.getString("access_token");
                System.out.println("Access Token: " + token); // 添加日志
                return token;
            } else {
                System.err.println("Failed to get access token. Status: " + response.getStatusCode());
                System.err.println("Response: " + response.getBody());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
